package com.sgroup.studycountry.application.service.impl;

import com.sgroup.studycountry.application.dto.UserInput;
import com.sgroup.studycountry.application.service.IUserService;
import com.sgroup.studycountry.domain.model.User;
import com.sgroup.studycountry.domain.repository.UserRepository;
import com.sgroup.studycountry.infrastructure.exception.EntityNotFoundException;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户服务实现
 *
 * @author umi
 * @date 2021/10/27 19:31
 */

@Service
@AllArgsConstructor
@Transactional(readOnly = true)
public class IUserServiceImpl implements IUserService {

    private final UserRepository userRepository;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public User insert(UserInput input) {
        return userRepository.save(input.convert());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public User update(String id, UserInput input) {
        User user = this.getById(id);
        input.convertAndUpdate(user);
        return user;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(String id) {
        userRepository.delete(this.getById(id));
        return true;
    }

    @Override
    public User getById(String id) {
        return userRepository.findById(id).orElseThrow(() -> new EntityNotFoundException(User.class, id));
    }

    @Override
    public User getByPhoneNumber(String phoneNumber) {
        return userRepository.getByPhoneNumber(phoneNumber).orElseThrow(() -> new EntityNotFoundException(User.class, phoneNumber));
    }

    @Override
    public void login(String phoneNumber, String password) {
        User user = this.getByPhoneNumber(phoneNumber);
        if (!user.getPassword().equals(password)) {
            throw new RuntimeException("账号或密码错误！");
        }
    }

}
